class Solution(object):
    def canBeValid(self, s, locked):
        n = len(s)
        st = 0
        qiankuo = 0
        for i in range(n):
            if locked[i] == '0':
                st += 1
            else:
                if s[i] == '(':
                    qiankuo += 1
                else:
                    qiankuo -= 1
                    if qiankuo < 0:
                        if st > 0:
                            st -= 1
                            qiankuo = 0
                        else:
                            return False
        if st < qiankuo or (st - qiankuo) % 2 == 1:
            return False
        st = 0
        houkuo = 0
        for i in range(n):
            if locked[n - 1- i] == '0':
                st += 1
            else:
                if s[n - 1 - i] == ')':
                    houkuo += 1
                else:
                    houkuo -= 1
                    if houkuo < 0:
                        if st > 0:
                            st -= 1
                            houkuo = 0
                        else:
                            return False
        if st < houkuo or (st - houkuo) % 2 == 1:
            return False
        else:
            return True

